package cn.brilliantfuture.commentry.util;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpUtil {
	private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);

	
	public static String getInvoke(String urlStr){
		// for (int i = 0; i < 3; i++) {
		URL url;
		InputStream inputStream = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		HttpURLConnection connection = null;
		String is;
		try {
			url = new URL(urlStr);
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.setUseCaches(false);
			connection.setReadTimeout(60000);
			logger.info("Connect, URL:" + urlStr);
			connection.connect();
			inputStream = connection.getInputStream();
			isr = new InputStreamReader(inputStream);
			br = new BufferedReader(isr);
			int c = -1;
			StringBuilder isb = new StringBuilder();
			while ((c = br.read()) >= 0) {
				isb.append((char) c);
			}
			is = isb.toString();
			return is;
//			break;
		} catch (FileNotFoundException e2) {
			logger.error("read return info error:" + urlStr, e2);
			return "error";
		} catch (SocketTimeoutException e) {
			logger.error("Wait timeout,pass it." + urlStr, e);
			return "error";
		} catch (IOException e1) {
			logger.error("IOException." + urlStr, e1);
			InputStream errStream = connection.getErrorStream();
			if (null == errStream)
				return "error";
			BufferedReader errbr = new BufferedReader(new InputStreamReader(errStream));
			StringBuilder errisb = new StringBuilder();
			int c = -1;
			try {
				while ((c = errbr.read()) >= 0) {
					errisb.append((char) c);
				}
				String errinfo = errisb.toString();
				logger.error(errinfo);
			} catch (IOException e) {
				logger.error("get Error info IOException.", e1);
				return "error";
			} finally {
				try {
					errStream.close();
					errbr.close();
				} catch (IOException e) {
					logger.error("get Error info close stream IOException.", e);
				}
			}
			logger.error("----------------------------------------------------------------------------------------");
			return "error";
		} finally {
			try {
				if (inputStream != null) {
					inputStream.close();
				}
				if (isr != null) {
					isr.close();
				}
				if (br != null) {
					br.close();
				}
			} catch (IOException e) {
				logger.error("Dispacher IOException", e);
			}
			connection.disconnect();
		}
		// }
	}

}
